import React, { memo, useState, useEffect, useMemo } from 'react';
import { 
  Card, 
  Button, 
  Row, 
  Col, 
  Space, 
  Typography, 
  Divider,
  Switch,
  Select,
  Slider,
  message,
  Modal,
  Upload,
  Progress,
  Alert,
  Form,
  Input,
  InputNumber,
  Tabs
} from 'antd';
import { 
  SettingOutlined,
  BgColorsOutlined,
  DownloadOutlined,
  UploadOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  InfoCircleOutlined,
  DeleteOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { useSettingsStore } from '@/store/settings';
import { dataImportExportService } from '@/services/dataManager';
import type { ThemeMode } from '@/types/common';
import type { UploadFile } from 'antd/es/upload/interface';
import styles from './SettingsPage.module.css';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
const { Dragger } = Upload;

/**
 * 设置页面组件
 * @description 提供主题切换、数据导入导出、用户偏好设置功能
 */
const SettingsPage: React.FC = memo(() => {
  // 本地状态
  const [activeTab, setActiveTab] = useState('appearance');
  const [exportLoading, setExportLoading] = useState(false);
  const [importLoading, setImportLoading] = useState(false);
  const [importProgress, setImportProgress] = useState(0);
  const [showImportResult, setShowImportResult] = useState(false);
  const [importResult, setImportResult] = useState<any>(null);

  // 状态管理
  const {
    themeMode,
    setThemeMode: setTheme,
    toggleTheme,
    followSystemTheme,
    setFollowSystemTheme,
    userPreferences,
    updateUserPreferences,
    resetUserPreferences,
    displaySettings,
    updateDisplaySettings,
    resetDisplaySettings,
    getSettingsSummary,
    resetAllSettings
  } = useSettingsStore();

  // 数据管理服务
  const dataImportExportService = useMemo(() => {
    return {
      exportAllData: async () => {
        const { dataImportExportService } = await import('@/services/dataManager');
        const result = await dataImportExportService.exportData();
        return result.success ? result.data : '';
      },
      importAllData: async (data: string) => {
        const { dataImportExportService } = await import('@/services/dataManager');
        return dataImportExportService.importData(data);
      },
      clearAllData: async () => {
        const { dataImportExportService } = await import('@/services/dataManager');
        return dataImportExportService.clearData();
      },
      getDataStatistics: async () => {
        const { dataImportExportService } = await import('@/services/dataManager');
        return dataImportExportService.getStatistics();
      }
    };
  }, []);

  // 数据统计
  const [dataStats, setDataStats] = useState({
    students: 0,
    courses: 0,
    categories: 0,
    templates: 0,
    instances: 0,
    totalSize: 0
  });

  // 获取数据统计
  useEffect(() => {
    const loadDataStats = async () => {
      try {
        const result = await dataImportExportService.getDataStatistics();
        if (result.success) {
          setDataStats({
            students: result.data.students,
            courses: result.data.courses,
            categories: result.data.courseCategories,
            templates: result.data.scheduleTemplates,
            instances: result.data.scheduleInstances,
            totalSize: result.data.totalSize
          });
        }
      } catch (error) {
        console.error('获取数据统计失败:', error);
      }
    };

    loadDataStats();
  }, []); // 移除服务依赖，避免无限循环

  // 主题选项
  const themeOptions = [
    { value: 'light' as ThemeMode, label: '浅色主题', icon: '☀️' },
    { value: 'dark' as ThemeMode, label: '深色主题', icon: '🌙' },
    { value: 'auto' as ThemeMode, label: '跟随系统', icon: '🔄' }
  ];

  // 语言选项
  const languageOptions = [
    { value: 'zh-CN', label: '简体中文' },
    { value: 'en-US', label: 'English' }
  ];

  // 导出数据
  const handleExportData = async () => {
    setExportLoading(true);
    try {
      const data = await dataImportExportService.exportAllData();
      const blob = new Blob([data], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `course-schedule-backup-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      message.success('数据导出成功');
    } catch (error) {
      console.error('导出数据失败:', error);
      message.error('导出数据失败，请重试');
    } finally {
      setExportLoading(false);
    }
  };

  // 导入数据
  const handleImportData = async (file: File) => {
    setImportLoading(true);
    setImportProgress(0);
    
    try {
      const text = await file.text();
      
      // 模拟进度更新
      const progressInterval = setInterval(() => {
        setImportProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + 10;
        });
      }, 100);

      const result = await dataImportExportService.importAllData(text);
      
      clearInterval(progressInterval);
      setImportProgress(100);
      
      setTimeout(() => {
        setImportResult(result);
        setShowImportResult(true);
        setImportLoading(false);
        setImportProgress(0);
        
        if (result.success) {
          message.success('数据导入成功');
        } else {
          message.error('数据导入失败');
        }
      }, 500);
      
    } catch (error) {
      console.error('导入数据失败:', error);
      message.error('导入数据失败，请检查文件格式');
      setImportLoading(false);
      setImportProgress(0);
    }
  };

  // 清除所有数据
  const handleClearAllData = () => {
    confirm({
      title: '确认清除所有数据',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
            ⚠️ 危险操作警告
          </p>
          <p>此操作将清除所有数据，包括：</p>
          <ul>
            <li>所有学生信息</li>
            <li>所有课程信息</li>
            <li>所有课程分类</li>
            <li>所有课程安排</li>
            <li>所有用户设置</li>
          </ul>
          <p style={{ color: '#ff4d4f' }}>
            此操作不可恢复，请确保已备份重要数据！
          </p>
        </div>
      ),
      okText: '确认清除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await dataImportExportService.clearAllData();
          message.success('所有数据已清除');
          // 刷新页面
          window.location.reload();
        } catch (error) {
          console.error('清除数据失败:', error);
          message.error('清除数据失败，请重试');
        }
      }
    });
  };

  // 重置设置
  const handleResetSettings = () => {
    confirm({
      title: '确认重置设置',
      icon: <ExclamationCircleOutlined />,
      content: '确定要重置所有设置到默认值吗？此操作不可恢复。',
      okText: '确认重置',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        resetUserPreferences();
        resetDisplaySettings();
        setTheme('auto');
        message.success('设置已重置');
      }
    });
  };

  // 上传配置
  const uploadProps = {
    name: 'file',
    multiple: false,
    accept: '.json',
    beforeUpload: (file: File) => {
      handleImportData(file);
      return false; // 阻止自动上传
    },
    showUploadList: false
  };

  return (
    <div className={styles.settingsPage}>
      {/* 页面头部 */}
      <div className={styles.pageHeader}>
        <div className={styles.headerContent}>
          <div className={styles.titleSection}>
            <Title level={2} className={styles.pageTitle}>
              <SettingOutlined /> 系统设置
            </Title>
            <Text type="secondary">
              个性化设置、数据管理和系统配置
            </Text>
          </div>
        </div>
      </div>

      <Divider />

      {/* 主要内容 */}
      <div className={styles.pageContent}>
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          className={styles.contentTabs}
        >
          {/* 外观设置 */}
          <TabPane 
            tab={
              <span>
                <BgColorsOutlined />
                外观设置
              </span>
            } 
            key="appearance"
          >
            <Row gutter={[24, 24]}>
              <Col xs={24} lg={12}>
                <Card title="主题设置" className={styles.settingCard}>
                  <div className={styles.settingItem}>
                    <div className={styles.settingLabel}>
                      <Text strong>主题模式</Text>
                      <Text type="secondary">选择您喜欢的主题外观</Text>
                    </div>
                    <Select
                      value={themeMode}
                      onChange={setTheme}
                      style={{ width: 150 }}
                    >
                      {themeOptions.map(option => (
                        <Option key={option.value} value={option.value}>
                          <span>{option.icon} {option.label}</span>
                        </Option>
                      ))}
                    </Select>
                  </div>

                  <Divider />

                  <div className={styles.settingItem}>
                    <div className={styles.settingLabel}>
                      <Text strong>紧凑模式</Text>
                      <Text type="secondary">减少界面元素间距</Text>
                    </div>
                    <Switch
                      checked={displaySettings.enableAnimations}
                      onChange={(checked) => updateDisplaySettings({ enableAnimations: checked })}
                    />
                  </div>

                  <div className={styles.settingItem}>
                    <div className={styles.settingLabel}>
                      <Text strong>显示动画</Text>
                      <Text type="secondary">启用界面过渡动画</Text>
                    </div>
                    <Switch
                      checked={displaySettings.showCourseColors}
                      onChange={(checked) => updateDisplaySettings({ showCourseColors: checked })}
                    />
                  </div>
                </Card>
              </Col>

              <Col xs={24} lg={12}>
                <Card title="显示设置" className={styles.settingCard}>
                  <div className={styles.settingItem}>
                    <div className={styles.settingLabel}>
                      <Text strong>语言</Text>
                      <Text type="secondary">选择界面语言</Text>
                    </div>
                    <Select
                      value={userPreferences.language}
                      onChange={(value) => updateUserPreferences({ language: value })}
                      style={{ width: 150 }}
                    >
                      {languageOptions.map(option => (
                        <Option key={option.value} value={option.value}>
                          {option.label}
                        </Option>
                      ))}
                    </Select>
                  </div>

                  <Divider />

                  <div className={styles.settingItem}>
                    <div className={styles.settingLabel}>
                      <Text strong>每页显示数量</Text>
                      <Text type="secondary">列表每页显示的项目数量</Text>
                    </div>
                    <InputNumber
                      min={10}
                      max={100}
                      step={10}
                      value={20}
                      onChange={(value) => console.log('pageSize changed:', value)}
                    />
                  </div>

                  <div className={styles.settingItem}>
                    <div className={styles.settingLabel}>
                      <Text strong>自动保存</Text>
                      <Text type="secondary">自动保存表单数据</Text>
                    </div>
                    <Switch
                      checked={false}
                      onChange={(checked) => console.log('autoSave changed:', checked)}
                    />
                  </div>
                </Card>
              </Col>
            </Row>
          </TabPane>

          {/* 数据管理 */}
          <TabPane 
            tab={
              <span>
                <DownloadOutlined />
                数据管理
              </span>
            } 
            key="data"
          >
            <Row gutter={[24, 24]}>
              <Col xs={24} lg={12}>
                <Card title="数据统计" className={styles.settingCard}>
                  <div className={styles.dataStats}>
                    <Row gutter={[16, 16]}>
                      <Col span={12}>
                        <div className={styles.statItem}>
                          <div className={styles.statNumber}>{dataStats.students}</div>
                          <div className={styles.statLabel}>学生</div>
                        </div>
                      </Col>
                      <Col span={12}>
                        <div className={styles.statItem}>
                          <div className={styles.statNumber}>{dataStats.courses}</div>
                          <div className={styles.statLabel}>课程</div>
                        </div>
                      </Col>
                      <Col span={12}>
                        <div className={styles.statItem}>
                          <div className={styles.statNumber}>{dataStats.categories}</div>
                          <div className={styles.statLabel}>分类</div>
                        </div>
                      </Col>
                      <Col span={12}>
                        <div className={styles.statItem}>
                          <div className={styles.statNumber}>{dataStats.templates}</div>
                          <div className={styles.statLabel}>课程模板</div>
                        </div>
                      </Col>
                      <Col span={24}>
                        <div className={styles.statItem}>
                          <div className={styles.statNumber}>{dataStats.instances}</div>
                          <div className={styles.statLabel}>课程实例</div>
                        </div>
                      </Col>
                    </Row>
                  </div>
                </Card>
              </Col>

              <Col xs={24} lg={12}>
                <Card title="数据备份" className={styles.settingCard}>
                  <div className={styles.backupSection}>
                    <Alert
                      message="数据备份建议"
                      description="建议定期备份数据，以防数据丢失。备份文件包含所有学生、课程、课表等信息。"
                      type="info"
                      showIcon
                      style={{ marginBottom: 16 }}
                    />
                    
                    <Space direction="vertical" style={{ width: '100%' }}>
                      <Button
                        type="primary"
                        icon={<DownloadOutlined />}
                        loading={exportLoading}
                        onClick={handleExportData}
                        block
                      >
                        导出数据备份
                      </Button>
                      
                      <Dragger {...uploadProps} className={styles.uploadArea}>
                        <p className="ant-upload-drag-icon">
                          <UploadOutlined />
                        </p>
                        <p className="ant-upload-text">点击或拖拽文件到此区域导入数据</p>
                        <p className="ant-upload-hint">
                          支持 JSON 格式的备份文件
                        </p>
                      </Dragger>
                      
                      {importLoading && (
                        <Progress 
                          percent={importProgress} 
                          status="active"
                          strokeColor={{
                            '0%': '#108ee9',
                            '100%': '#87d068',
                          }}
                        />
                      )}
                    </Space>
                  </div>
                </Card>
              </Col>

              <Col xs={24}>
                <Card title="危险操作" className={styles.dangerCard}>
                  <Alert
                    message="危险操作警告"
                    description="以下操作可能导致数据丢失，请谨慎操作并确保已备份重要数据。"
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                  />
                  
                  <Space>
                    <Button
                      danger
                      icon={<DeleteOutlined />}
                      onClick={handleClearAllData}
                    >
                      清除所有数据
                    </Button>
                    
                    <Button
                      icon={<ReloadOutlined />}
                      onClick={handleResetSettings}
                    >
                      重置所有设置
                    </Button>
                  </Space>
                </Card>
              </Col>
            </Row>
          </TabPane>

          {/* 系统信息 */}
          <TabPane 
            tab={
              <span>
                <InfoCircleOutlined />
                系统信息
              </span>
            } 
            key="system"
          >
            <Row gutter={[24, 24]}>
              <Col xs={24} lg={12}>
                <Card title="应用信息" className={styles.settingCard}>
                  <div className={styles.systemInfo}>
                    <div className={styles.infoItem}>
                      <Text strong>应用名称：</Text>
                      <Text>课程表管理系统</Text>
                    </div>
                    <div className={styles.infoItem}>
                      <Text strong>版本号：</Text>
                      <Text>v1.0.0</Text>
                    </div>
                    <div className={styles.infoItem}>
                      <Text strong>构建时间：</Text>
                      <Text>{new Date().toLocaleDateString()}</Text>
                    </div>
                    <div className={styles.infoItem}>
                      <Text strong>技术栈：</Text>
                      <Text>React + TypeScript + Ant Design</Text>
                    </div>
                  </div>
                </Card>
              </Col>

              <Col xs={24} lg={12}>
                <Card title="浏览器信息" className={styles.settingCard}>
                  <div className={styles.systemInfo}>
                    <div className={styles.infoItem}>
                      <Text strong>浏览器：</Text>
                      <Text>{navigator.userAgent.split(' ')[0]}</Text>
                    </div>
                    <div className={styles.infoItem}>
                      <Text strong>语言：</Text>
                      <Text>{navigator.language}</Text>
                    </div>
                    <div className={styles.infoItem}>
                      <Text strong>屏幕分辨率：</Text>
                      <Text>{screen.width} × {screen.height}</Text>
                    </div>
                    <div className={styles.infoItem}>
                      <Text strong>本地存储：</Text>
                      <Text>
                        {typeof Storage !== 'undefined' ? '支持' : '不支持'}
                      </Text>
                    </div>
                  </div>
                </Card>
              </Col>

              <Col xs={24}>
                <Card title="使用说明" className={styles.settingCard}>
                  <Paragraph>
                    <Title level={4}>功能介绍</Title>
                    <ul>
                      <li><strong>学生管理：</strong>添加、编辑、删除学生信息，支持批量操作</li>
                      <li><strong>课程管理：</strong>管理课程信息和分类，支持多分类归属</li>
                      <li><strong>课表管理：</strong>安排课程时间，支持周期性课程和冲突检测</li>
                      <li><strong>混合显示：</strong>同时查看多个学生的课程表</li>
                      <li><strong>数据备份：</strong>导出和导入数据，确保数据安全</li>
                    </ul>
                  </Paragraph>
                  
                  <Paragraph>
                    <Title level={4}>使用建议</Title>
                    <ul>
                      <li>定期备份数据，避免意外丢失</li>
                      <li>合理设置课程分类，便于管理</li>
                      <li>注意时间冲突提示，避免课程安排冲突</li>
                      <li>使用搜索和筛选功能快速找到目标信息</li>
                    </ul>
                  </Paragraph>
                </Card>
              </Col>
            </Row>
          </TabPane>
        </Tabs>
      </div>

      {/* 导入结果模态框 */}
      <Modal
        title="数据导入结果"
        open={showImportResult}
        onCancel={() => setShowImportResult(false)}
        footer={[
          <Button key="close" onClick={() => setShowImportResult(false)}>
            关闭
          </Button>
        ]}
      >
        {importResult && (
          <div>
            {importResult.success ? (
              <Alert
                message="导入成功"
                description={`成功导入 ${importResult.imported} 条记录`}
                type="success"
                showIcon
                style={{ marginBottom: 16 }}
              />
            ) : (
              <Alert
                message="导入失败"
                description={importResult.error}
                type="error"
                showIcon
                style={{ marginBottom: 16 }}
              />
            )}
            
            {importResult.details && (
              <div>
                <Title level={5}>导入详情：</Title>
                <ul>
                  {Object.entries(importResult.details).map(([key, value]) => (
                    <li key={key}>
                      {key}: {String(value)}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
});

SettingsPage.displayName = 'SettingsPage';

export default SettingsPage;